#include "tools.h"
#include "sys/types.h"
#include "sys/socket.h"
#include <pthread.h>

// deal with the request of client in a thread
void *do_data(void* fd){
    // steps:
    // 1. define relevant data
    // 2. recv
    int sockfd = *((int*)fd);

    char buff[1024] = {0};

    int bytes;

    // recv
    for (;;){
        if ((bytes = recv(sockfd, buff, sizeof(buff), 0)) <= 0){
            perror("recv");
            break;
        }
        info("get message: %s\n", buff);

        if (strncmp(buff, "bye", 3) == 0){
            // say goodbye
            write(sockfd, "good bye", 8);
            break;
        } else {
            // print back the message
            write(sockfd, buff, bytes);
        }
    }

    // close and exit
    close(sockfd);
    pthread_exit(NULL);
}

int main(void){

    struct sockaddr_in addr;

    int sockfd = getTcpServerSocket(8888);

    addr.sin_port = htons(8888);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    int len = sizeof(addr);
    for (;;){
        pthread_t thread;
        int* fd = (int*)malloc(sizeof(int));
        if (*fd < 0){
            perror("getfd");
            exit(-1);
        }
        info("waiting for client connection at %d", 8888);
        if ((*fd = accept(sockfd, (struct sockaddr*)&addr, &len)) < 0){
            perror("accept");
            exit(-1);
        }
        info("get new connection");

        if (pthread_create(&thread, NULL, do_data, fd) < 0){
            perror("pthread_create");
            exit(-1);
        }
    }

    return 0;
}
